<?php

namespace App\Task;


use App\Model\Applet;
use App\Model\DataBackhaulSetting;
use App\Model\DataPaymentBackhaul;
use App\Model\DataPaymentSettle;
use App\Model\DataSpread;
use App\Model\PlayletBind;
use App\Model\Payment;
use App\Model\SystemOrderDay;
use App\Model\SystemOrderDayCount;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class CheckPaymentSettleTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";

    public static $getSettleUrl = "https://open.douyin.com/api/trade_basic/v1/developer/settle_query";
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'CheckPaymentSettle');
    }

    public function execute()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取今天的2个小时内的的订单');

        $startDate = date('Y-m-d H:i:s',time()-43200);
        $endDate = date('Y-m-d H:i:s',time());

        $this->logger->info('开始时间为：'.$startDate);
        $this->logger->info('结束时间为：'.$endDate);
        try {
            $orderKey =  'check_payment_settle_live';
            $keyData = $redis->get($orderKey);
            if(!empty($keyData)){
//                $redis->del($orderKey);
                $this->logger->info('存在处理中的订单进程');
                $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单进行查询分账');
                return;
            }else{
                $redis->set($orderKey,1);
            }
            //当前时间7天前，2个小时内的订单，半个小时跑一次脚本
            $settleData = DataPaymentSettle::query()
                ->select(['id','status','applet_id','out_order_no'])
                ->where('status','=',2)
                ->where('created_at','>=',$startDate)
                ->where('created_at','<=',$endDate)
                ->get();

            //获取所有抖音小程序
            $appletData = Applet::query()->where(['type' => 2])->select(['id','app_id','app_secret'])->get();

            if($settleData->isNotEmpty() && $appletData->isNotEmpty()) {

                $this->logger->info('分账订单的数据为数量为：', [count($settleData)]);
                //整合小程序信息
                $appletKeyVal = array();

                foreach ($appletData as $appletDatum){

                    $appletKeyVal[$appletDatum->id] = $appletDatum->toArray();
                }
                foreach ($settleData as $settleDatum) {

                    $applet_id = $settleDatum->applet_id;

                    $out_order_no = $settleDatum->out_order_no;
                    //处理中
                    if ($settleDatum->status == 2) {
                        //查询是否有对应的小程序信息
                        if(!empty($appletKeyVal[$applet_id])){

                            $appletInfo = $appletKeyVal[$applet_id];
                            //本地测试
                            if(!empty(env('DY_TEST_TOKEN'))){
                                $accessToken = env('DY_TEST_TOKEN');
                            }else{
                                $accessToken = $this->getDyAccessToken($appletInfo['id'],$appletInfo['app_id'],$appletInfo['app_secret']);
                            }
                            if(!empty($accessToken)){

                                $settleInfo = $this->getsettleInfo($out_order_no,$appletInfo['app_id'],$accessToken);
                                if(!empty($settleInfo)){
                                    $this->logger->error('发起分账成功',[$settleDatum->id]);
                                    if($settleInfo['settle_status'] == 'SUCCESS'){
                                        $settleDatum->settle_id = $settleInfo['settle_id'] ?? '';
                                        $settleDatum->settle_detail = $settleInfo['settle_detail'] ?? '';
                                        $settleDatum->commission = $settleInfo['commission'] ?? '';
                                        $settleDatum->order_id = $settleInfo['order_id'] ?? '';
                                        $settleDatum->out_settle_no = $settleInfo['out_settle_no'] ?? '';
                                        $settleDatum->settle_at = date('Y-m-d H:i:s',$settleInfo['settle_at']/1000) ?? '';
                                        $settleDatum->rake = $settleInfo['rake'] ?? '';
                                        $settleDatum->settle_amount = $settleInfo['settle_amount'] ?? '';
                                        $settleDatum->settle_status = $settleInfo['settle_status'] ?? '';
                                        $settleDatum->status =3;
                                        $settleDatum->save();
                                    }else if($settleInfo['settle_status'] == 'FAIL'){
                                        $settleDatum->settle_status = $settleInfo['settle_status'] ?? '';
                                        $settleDatum->status =4;
                                        $settleDatum->save();
                                    }else if($settleInfo['settle_status'] == 'PROCESSING'){
                                        $settleDatum->settle_status = $settleInfo['settle_status'] ?? '';
                                        $settleDatum->save();
                                    }
                                }else{
                                    $this->logger->error('发起分账错误',[$settleDatum->id]);
                                }
                            }else{
                                $this->logger->error('token出现错误',[$settleDatum->id]);
                            }
                        }else{
                            $this->logger->error('订单没有对应的小程序',[$settleDatum->id]);
                        }
                    }
                }
            } else{
                $this->logger->info('没有订单需要处理');
            }
            $redis->del($orderKey);

        }catch (\Exception $e){
            $redis->del($orderKey);
            $this->logger->error('请求订单|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单数据');
    }

    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        $this->logger->info('抖音token为：'.$accessToken);
        return $accessToken;
    }

    public function getsettleInfo($out_order_no,$app_id,$accessToken){

        try {
            $params         = [
                "app_id"   =>$app_id,
                "out_order_no"   => $out_order_no
            ];
            $taskUrl = self::$getSettleUrl;
            $this->logger->info('查询分账信息数据：'.PHP_EOL.var_export(['result' => $params], true));
            $this->logger->info('查询分账信息Url：'.$taskUrl);
            $postResult  = $this->request($params, $taskUrl,'POST',$accessToken);
            if($postResult['err_no'] == 0){
                $this->logger->info('查询分账信息接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
                return $postResult['data'][0];
            }else{
                $this->logger->error('查询分账信息接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            }
        }catch (\Exception $e){
            $this->logger->error('请求抖音分账错误'.$e->getMessage(),[$e->getLine()]);
        }
        return false;
    }


    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}